<template>
  <div>

    <el-dialog v-model="open" :title="title" :close-on-click-modal='false' width="500px" append-to-body>
	  
	  <el-tree ref="treeRef" :data="treedata" v-loading="loading" show-checkbox node-key="id" 
	     :default-expanded-keys="[treedata[0] ? treedata[0].id : '0']" :check-strictly="checkStrictly" 
		 :props="defaultProps">
	  </el-tree>
 
	  <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
	 
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, toRef } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";

// 是否打开弹出框
const open = ref(false);
// 弹出框标题
const title = ref("");

const currentRoleId = ref(null);

let treeRef = ref([]);

let treedata = ref([]);

// 是否加载
const loading = ref(true);

const defaultProps = {
  id: 'id',
  parentId: 'parentId',
  label: 'name',
  children: 'children'
};

const checkStrictly = ref(false);


// 查询参数
const queryForm = reactive({
  name: ""
});

// 提交表单数据
let form = toRef(
  reactive({
    roleId: "",
    menuIdList: []
  })
);

/**
 * 查询树
 */
const getTreeTable = () => {
  loading.value = true;
  baseService.get("/system/menu/treeTable", queryForm)
    .then((res) => {
      loading.value = false;
      if (res.code === 200) {
        treedata.value = res.data;
      } else {
        treedata.value = [];
      }
    })
    .catch(() => {
      loading.value = false;
    });
};


const emit = defineEmits(["callBack"]);//声明事件(父级页面上添加的 @监听事件)

//定义类型
interface Role {
  code: string
  name: string
  id: string
};

//父调子的子
const permsFormShow = (titleName: string, row: Role) => {
  open.value = true;
  title.value = titleName; 
  currentRoleId.value = row.id;
  
  getTreeTable();
  
  //先解除关联
  checkStrictly.value = true; 
  baseService.get(`/system/roleMenu/getMenuIdListByRoleId?roleId=${row.id}`).then((res) => {
    if (res.code === 200) {
  
	  nextTick(() => {
		treeRef.value.setCheckedKeys(res.data);
		setTimeout(() => {
		  //恢复联动
		  checkStrictly.value = false; 
		}, 0);
	  });
	  
    }
  });
  
};

/**
 * 提交按钮
 */
const submitForm = async() => {
  const checkedValue = treeRef.value.getCheckedKeys();
  const halfCheckedValue = treeRef.value.getHalfCheckedKeys();
  const finalValue = [...checkedValue, ...halfCheckedValue];

  form.value.roleId = currentRoleId.value;
  form.value.menuIdList = finalValue;
   
  baseService.post(`/system/roleMenu/saveRoleMenuIdList`, form.value).then((res) => {
    if(res.code === 200) {
      ElMessage.success(res.msg);
      open.value = false;
      emit("callBack");
    }else {
      ElMessage.error(res.msg);
    }
  });
  
};


defineExpose({
  permsFormShow
}) //将子组件方法暴露出来，让父组件调用
</script>

<style scoped></style>
